package com.example.administrator.xxnapp.tucao;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Base64;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.administrator.xxnapp.BaseActivity;
import com.example.administrator.xxnapp.R;
import com.example.administrator.xxnapp.bean.ImageBean;
import com.example.administrator.xxnapp.bean.TuCaoBean;
import com.example.administrator.xxnapp.bean.UserBean;
import com.example.administrator.xxnapp.http.CustomStringCallback;
import com.example.administrator.xxnapp.util.Config;
import com.example.administrator.xxnapp.util.des3.Des3;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.mdruby.baselibrary.utils.KeySoftUtil;
import cn.mdruby.baselibrary.utils.ObjectStoreUtil;
import cn.mdruby.pickphotovideoview.MediaModel;
import cn.mdruby.pickphotovideoview.PickConfig;
import cn.mdruby.pickphotovideoview.PickData;
import cn.mdruby.pickphotovideoview.PickPhotoView;

public class SendTuCaoActivity extends BaseActivity implements IViewSendTuCao{
    private SendTuCaoPresenter mSendPresenter;
    @BindView(R.id.act_tucao_ET_content)
    EditText mETContent;
    @BindView(R.id.act_tucao_IV_Gallery)
    ImageView mIVGallery;
    @BindView(R.id.act_tucao_RV)
    RecyclerView mRV;
    private List<ImageBean> mImageDatas;
    private RVImageAdapter mImageAdapter;
    private UserBean mUser;

    @Override
    public int getLayoutId() {
        return R.layout.activity_tu_cao;
    }

    @Override
    public void initBeforeDatas() {
        mUser = (UserBean) ObjectStoreUtil.getObject(mContext, Config.Key.USER_OBJECT_KEY);
        mImageDatas = new ArrayList<>();
        mSendPresenter = new SendTuCaoPresenter(this,new TuCaoBean());
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
    }

    @Override
    public void setListeners() {
        mImageAdapter = new RVImageAdapter(mContext,mImageDatas);
        mRV.setLayoutManager(new GridLayoutManager(mContext,4));
        mRV.setAdapter(mImageAdapter);

        mRV.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (mImageDatas.size()==0){
                    if (KeySoftUtil.isSoftShowing(SendTuCaoActivity.this)){
                        KeySoftUtil.hideSoftInput(mETContent);
                    }else {
                        Toast.makeText(mContext, "==", Toast.LENGTH_SHORT).show();
                        KeySoftUtil.showSoftInput(mETContent);
                    }
                }
                return false;
            }
        });
    }

    @OnClick(R.id.act_tucao_TV_Send)
    public void sendTuCao(View view){
        mSendPresenter.sendTuCao(mUser.getUserId(),mETContent.getText().toString());
    }

    @OnClick(R.id.act_tucao_IV_Gallery)
    public void gallery(View view){
        new PickPhotoView.Bulid(mContext)
                .showVideo(false)
                .useLocalCamera(true)
                .showCamera(true)
                .setCanZip(true)
                .setCount(9)
                .start();
    }

    @Override
    public void sendTuCaoSuccess(int userId, int tucaoId) {
        if (mImageDatas.size()>0){
            List<File> files = new ArrayList<>();
            for (ImageBean bean :
                    mImageDatas) {
                files.add(new File(bean.getPath()));
            }
            mSendPresenter.upLoadImage(userId,tucaoId,files);
        }else {
//            setResult(RESULT_OK,getIntent());
//            this.finish();
            upLoadImageSuccess();
        }
    }

    @Override
    public void upLoadImageSuccess() {
        setResult(RESULT_OK,getIntent());
        this.finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK){
            switch (requestCode){
                case PickConfig.RequestCode.SELECT_PHOTO:
                    List<MediaModel> mediaModels = (List<MediaModel>) data.getSerializableExtra(PickConfig.KEY.MEDIA_FILE_DATA);
                    List<File> files = new ArrayList<>();
                    for (MediaModel model :
                            mediaModels) {
                        ImageBean bean = new ImageBean();
                        bean.setPath(model.getFile().getAbsolutePath());
                        files.add(new File(model.getFile().getAbsolutePath()));
                        mImageDatas.add(bean);
                    }

                    mImageAdapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    /**
     * 加密
     * @param message  原文
     * @param key    密钥
     * @return
     * @throws Exception
     */
    public static String EncryptAsDoNet(String message, String key)throws Exception {

        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
        byte[] encryptbyte = cipher.doFinal(message.getBytes());
        return new String(Base64.encode(encryptbyte, Base64.DEFAULT));

    }

    /**
     * 解密
     * @param message 密文
     * @param key   密钥
     * @return
     * @throws Exception
     */
    public static String DecryptDoNet(String message, String key)throws Exception {
        byte[] bytesrc = Base64.decode(message.getBytes(), Base64.DEFAULT);
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
        cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
        byte[] retByte = cipher.doFinal(bytesrc);
        return new String(retByte);

    }


}
